<!--隐患清单-->
<template>
  <Layout>
    <Form ref="queryForm" :model="dataToQuery" :label-width="120">
      <Row class="query-form">
        <Col span="8">
          <FormItem label='隐患上报单位：'>
            <cascaderDom class="query-form-el" ref="queryOrgCascader" style="width: 100%;"
                         @setOrgInfo='setOrgId'
                         @setOrgname='setOrgName'
                         :orgTree="true"></cascaderDom>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label='隐患等级：'>
            <Select   v-model="dataToQuery.dangerLevel"
                    :label-in-value="true" placeholder="请选择隐患等级" clearable = 'true'>
              <Option v-for="item in dangerLevels" :value="item.codingCodeId"
                      :key="item.codingCodeId">{{ item.codingName }}
              </Option>
            </Select>
          </FormItem>
        </Col>


        <Col span="8" v-if="!switchFlag">
          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
        <Col span="8" v-else>
          <FormItem label='隐患协调：'>
            <Select   v-model="dataToQuery.dangerSort"
                      :label-in-value="true" placeholder="请选择隐患协调">
              <Option value="1">企业内部</Option>
              <Option value="2">跨企业</Option>
              <Option value="3">跨二级集团</Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label='整改责任人：' prop='persionHeld'>
            <Input  class='' placeholder="请填写整改责任人" type='text' v-model='dataToQuery.persionHeld'></Input>
          </FormItem>
        </Col>


      </Row>
      <Row v-show="switchFlag" class="query-form">

        <Col span="8" :offset="16">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
    </Form>
    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
           :loading='pageStatus.loading ||  pageStatus.baseLoading'
           border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
      </Col>
    </Row>
    <Modal :mask-closable="false" :title="mode == 'view' ?'隐患清单详情':'隐患清单'" :transfer=false v-model="dialogShow" v-if="dataToView && dialogShow"
           :width=800 :styles="{height:'559px'}" class-name='limit-height-dialog'>
      <Row>
        <Col span="24">
          <Form ref="dataToView" :class="mode === 'view'?'modal-view-detail':'modal-form'" :show-message="false"
                :model="dataToView" :rules="mode === 'view'?{} :ruleCustom"
                :label-position="mode === 'view'?'right':'top'" :label-width="mode === 'view'?160:null">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='隐患上报单位：' prop='companyId'>
                  <div v-if="mode === 'view'">{{ dataToView.companyName }}</div>
                  <cascaderDom v-else  class="query-form-el" ref="groupOrg"
                               @setOrgInfo='(data)=>{cascaderDomIdChangeHandle(data,"companyId");}'
                               @setOrgname='(data)=>{cascaderDomNameChangeHandle(data,"companyName");}'
                               :currentOrgId = "dataToView.companyId"
                               :setCurrentName="{label:dataToView.companyName, value:dataToView.companyId}"
                               :orgTree="true" ></cascaderDom>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='所属二级集团：' >
                  <div v-if="mode === 'view'">{{ dataToView.twoLevelOrgName }}</div>
                  <Input v-else class='' placeholder="请填写所属二级集团" type='text'
                         v-model='dataToView.twoLevelOrgName' readonly></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='隐患名称：' prop='dangerName'>
                  <div v-if="mode === 'view'">{{ dataToView.dangerName }}</div>
                  <Input v-else class='' placeholder="请填写隐患名称" type='text' v-model='dataToView.dangerName'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='隐患部位：' prop='dangerPosition'>
                  <div v-if="mode === 'view'">{{ dataToView.dangerPosition }}</div>
                  <Input v-else class='' placeholder="请填写隐患部位" type='text' v-model='dataToView.dangerPosition'></Input>
                </FormItem>
              </Col>
            </Row>

            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='隐患等级：' prop='dangerLevel'>
                  <div v-if="mode === 'view'">{{ dataToView.dangerLevelName }}</div>
                  <Select v-else  v-model="dataToView.dangerLevel"
                          :label-in-value="true" placeholder="请选择隐患等级" clearable = 'true'>
                    <Option v-for="item in dangerLevels" :value="item.codingCodeId"
                            :key="item.codingCodeId">{{ item.codingName }}
                    </Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='隐患协调：' prop='dangerSort'>
                  <div v-if="mode === 'view'">{{areaCodeToSortName(dataToView.dangerSort)}}</div>
                  <Cascader v-else :data="areaTree" v-model="dataToView.dangerSortArr" change-on-select :transfer="true"
                            @on-change="(value,selectedData)=>{$set(dataToView,'dangerSort',value.join(','))}"></Cascader>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='整改责任人：' prop='persionHeld'>
                  <div v-if="mode === 'view'">{{ dataToView.persionHeld }}</div>
                  <Input v-else class='' placeholder="请填写整改责任人" type='text' v-model='dataToView.persionHeld'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='责任部门：' prop='department'>
                  <div v-if="mode === 'view'">{{ dataToView.department }}</div>
                  <Input v-else class='' placeholder="请填写责任部门" type='text' v-model='dataToView.department'></Input>
                </FormItem>
              </Col>

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='计划整改完成时间：' prop='dangerDate'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.dangerDate) }}</div>
                  <DatePicker v-else class="w" placeholder="请选择计划整改完成时间" v-model='dataToView.dangerDate'></DatePicker>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='填报日期：' prop='createDate'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                  <DatePicker readonly v-else class="w" placeholder="请选择填报日期" v-model='dataToView.createDate'></DatePicker>
                </FormItem>
              </Col>

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg" v-if="mode === 'view'">
              <Col span="23" >
                <FormItem label='上报人：' prop='createUserName'>
                  <div >{{ dataToView.createUserName }}</div>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='产生原因分析：' >
                  <div v-if="mode === 'view'">{{ dataToView.causeAnalysis }}</div>
                  <Input v-else class='' placeholder="请填写产生原因分析" type='textarea' v-model='dataToView.causeAnalysis'></Input>
                </FormItem>
              </Col>
            </Row>

          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dataToView')">确定</Button>
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
        <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
      </div>
    </Modal>
  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import {sessionStorage} from '@/common/cacheUtils.js';
import {formatDate} from '@/tools/index'
import pageCommonFunction from '@/components/pageCommonFunction.js'

var cascaderDom = () => import('@/components/cascader-dom.vue');
export default {
  components: {
    cascaderDom
  },
  data() {
    return {
      ...this.createCommonDataField(),
      switchFlag: false,
      uploadFile:null,
      buttonLoading1:false,
      importModal:false,
      token:sessionStorage('token').get('Authorization'),
      columns1: [
        { title: '序号', width: 80, fixed: 'left', align: 'center', render: this.indexColumnsRender},
        {key: 'dangerName', title: '隐患名称', align: 'center',minWidth: 200,},
        {key: 'companyName', title: '隐患上报单位', align: 'center',minWidth: 200,},
        {key: 'twoLevelOrgName', title: '所属二级集团', align: 'center',minWidth: 200,tooltip:true},
        {key: 'dangerPosition', title: '隐患部位', align: 'center',minWidth: 120,tooltip:true},
        {key: 'dangerLevelName', title: '隐患等级', align: 'center',minWidth: 120,},
        {key: 'dangerSort', title: '隐患协调', align: 'center',minWidth: 150,render: (h, params) =>{ return h('span', this.sortNameToTable(params.row.dangerSort));}},
        {key: 'required', title: '是否需要集团协调', align: 'center',minWidth: 120,render: (h, params) =>{ return h('span', this.requireNameToTable(params.row.required));}},
        {key: 'persionHeld', title: '整改责任人', align: 'center',minWidth: 120,},
        {key: 'phone', title: '整改责任人电话', align: 'center',minWidth: 120,},
        {key: 'department', title: '责任部门', align: 'center',minWidth: 120,},
        {key: 'dangerDate', title: '计划整改完成时间', align: 'center',minWidth: 120,render: this.renderCellDate},
        {key: 'causeAnalysis', title: '产生原因分析', align: 'center',minWidth: 120,tooltip:true},
        {key: 'createDate', title: '填报日期', align: 'center',minWidth: 120,render: this.renderCellDate},
        {key: 'createUserName', title: '上报人', align: 'center',minWidth: 120},

        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          minWidth: 100,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '12px',
                },
                on: {
                  click: () => {
                    this.save(params.row);
                  }
                }
              }, '选择'),
            ]);
          }
        }
      ],
      upUrl:Api.uploadDangerList,
      ruleCustom: {
        dangerName: [{required: true, message: '请填写隐患名称', trigger: 'change',}],
        companyId: [{required: true, message: '请填写隐患上报单位', trigger: 'change',}],
        twoLevelOrgId: [{required: true, message: '请填写所属二级集团', trigger: 'change',}],
        dangerPosition: [{required: true, message: '请填写隐患部位', trigger: 'change',}],
        dangerLevel: [{required: true, message: '请填写隐患等级', trigger: 'change',}],
        dangerSort: [{required: true, message: '请填写隐患分类', trigger: 'change',}],
        persionHeld: [{required: true, message: '请填写整改责任人', trigger: 'change',}],
        causeAnalysis: [{required: true, message: '请填写产生原因分析', trigger: 'change',}],
        department: [{required: true, message: '请填写责任部门', trigger: 'change',}],
        dangerDate: [{required: true, message: '请填写计划整改完成时间', trigger: 'change', type: 'date'}],
        createDate: [{required: true, message: '请填写填报日期', trigger: 'change', type: 'date'}],


      },
      tableHeight: 10,
      areaMap:{},
      areaTree:[],
      dangerLevels:[],
      // api
      standardSelectModal: false,
      queryUrl: Api.queryDangerList,
      deleteUrl: Api.deleteDangerList,
      updateUrl: Api.updateDangerList,
      saveUrl: Api.saveDangerList,
      buttonLoading: false
    }
  },
  async mounted() {
    let _this = this;
    this.dataToQuery = {};
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 200;
    this.pageStatus.baseLoading = true;
    this.$http.get(Api.queryCodeDetailBySortId + '/DL-00001', {params: {}}).then((res) => {
      _this.dangerLevels = res.data.data
    });
    this.pageStatus.baseLoading = false
    this.query();
  },
  methods: {

    ...pageCommonFunction,
    cancel(){

    },
    requireNameToTable(code){
      if(!code || code === "") return "";

      if (code == '1'){
        return "是";
      }else if(code == '0'){
        return "否";
      }else{
        return "--"
      }
    },
    sortNameToTable(codeStr){
      if(!codeStr || codeStr === "") return "";

      if (codeStr == '1'){
        return "企业内部";
      }else if(codeStr == '2'){
        return "跨企业";
      }else if (codeStr == '3'){
        return "跨二级集团"
      }
    },
    save(row) {
      this.$emit('select', row);
    },
    dictListToMap(arr, key = 'codingCodeId') {
      var map = {}
      arr.map(item => {
        map[item[key]] = item
      })
      return map
    },
    areaCodeToSortName(codeStr){
      if(!codeStr || codeStr === "") return "";
      var arr = codeStr.split(',')
      var outArr = []
      arr.forEach(codingCodeId => {
        if (this.areaMap[codingCodeId]) {
          outArr.push(this.areaMap[codingCodeId].codingName)
        }
      })
      return outArr.join("·")
    },
    downloadMod(){
      this.buttonLoading1 = true
      this.$http.get(Api.downloadModDangerList, {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = "隐患清单导入模版.xlsx" //标题
        aLink.click()
        document.body.appendChild(aLink)
        this.buttonLoading1 = false
      })
    },
    importDanger(){
      this.importModal = true;
    },

    deleteData(params) {
      this.deleteDateAjax(params);
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = this.tableHeight + 44;

      } else {
        this.tableHeight = this.tableHeight - 44;
      }

    },
    setOrgId(data) {
      this.dataToQuery.companyId = data[data.length - 1];
    },
    setOrgName(data) {

    },
    query() {

      this.queryAjax()
    },

    submit(name) {

      this.submitAjax(name);
    },
    createEmptyDataToAdd() {
      return {
        companyId: sessionStorage('userId').getObject('userId').companyId,
        companyName: sessionStorage('userId').getObject('userId').companyName,
        twoLevelOrgId: sessionStorage('userId').getObject('userId').twoLevelOrgId,
        twoLevelOrgName: sessionStorage('userId').getObject('userId').twoLevelOrgName,
        createDate:new Date()
      }
    },
    downloadFile() {
      this.buttonLoading = true
      this.$http.get(Api.downloadDangerList, {
        params: this.dataToQuery,
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = "隐患清单(" + formatDate(new Date(), "yyyy-MM-dd") + ").xlsx" //标题
        aLink.click()
        document.body.appendChild(aLink)
        this.buttonLoading = false
      })
    },
  },
  watch: {},

}
</script>

<style lang='css' scoped>
@import '../../../index.css';

.importDanger{
  display:inline-block
}
</style>
